using UnityEngine;
using System.Collections;

public class CharacterMove : MonoBehaviour {
	
	public int _dialogCall;
	public float _Speed;
	public float _JumpAmount;
	public bool _Wait;
	public GameObject dialogObject;
	public GameObject answerObject;
	public GameObject interagir;
	public Loading load;
	public Axis _AxisJump;
	public Axis _AxisLeft;
	public Axis _AxisRight;
	public Dialog _generatorDialog;
	public tk2dAnimatedSprite anim;
	public AnimationChar animate;
	DialogText myDialogText;
	bool isFlip;
	string[] textReader;
	string name;
	int _Count;
	int _TextLimit;
	Vector2 positionDialog;
	public Missions objetivos;
	string saveMessage;
	bool isConclude;
	bool isNew;
	string sceneLoading;
	GameObject newMissionObj;
	int posAnswer;
	bool isAnswer;
	bool isRetributivista;
	int countSpaceInteract;
	GameObject pressStart;
	GameObject talk;
	GameObject save;
	bool objetiva;
	GameObject desative;
	GameObject active;
	public EticaPersonagem etica;
	public GameObject[] npcs;
	int missoesRealizadas = 7	;
	void Awake()
	{
		anim = GetComponent<tk2dAnimatedSprite>();	
	}
	
	void Update () 
	{

		//Quando o dialogo é iniciado, Entra esta parte
		if(_Wait)
		{
			//faz a chamada após apertar o espaço
			if(Input.GetKeyDown(KeyCode.Space))
			{
				//Ve se existe um dialogObject, caso sim ele irá destruir
				if(dialogObject)
				{
					Destroy(dialogObject);
				}
				
				//Soma a variavel que administra qual string preservar
				_Count ++;
				
				// Verifica se não existe nenhum texto no dialogo
				if(_Count >= _TextLimit)
				{
					if(isConclude)
					{
						MissionConclusion(saveMessage);	
					}
					if(isNew)
					{
						newMission(saveMessage,sceneLoading);
					}
					
					isConclude = false;
					_Count = 0;
					isNew = false;
					_Wait = false;
					animate.enabled = true;
					_dialogCall = 0;
					countSpaceInteract = 0;
				}
				
				// Se existir, ele chama o metodo para criar um novo dialogo
				else
				{
					string textForSend = textReader[_Count];
					ReadText(textForSend);
				}
				
			}
		}
		
		if(!_Wait)
		{
			//Andar para direita
			if(Input.GetAxis("Horizontal") > 0 && !_AxisRight.isGrounded)
			{
				transform.Translate((Vector3.right * _Speed) * Time.deltaTime);
			
				//Verifica se pode virar
				if(isFlip)
				{
					//Vira o personagem e fala que não pode mais virar para esta direção
					anim.FlipX();
					isFlip = false;
				}
			}
		
			//Andar para esquerda
			if(Input.GetAxis("Horizontal") < 0 && !_AxisLeft.isGrounded)
			{
				transform.Translate(-(Vector3.right * _Speed) * Time.deltaTime);
				
				//Verifica se pode virar
				if(!isFlip)
				{
					//Vira o personagem e fala que não pode mais virar para esta direção
					anim.FlipX();
					isFlip = true;
				}
			}
		
			//Faz o pulo
			if(Input.GetKeyDown("up") || Input.GetKeyDown("w"))
			{
				if(_AxisJump.isGrounded)
				{
					Jump();
				}
			}

		}
	}
	
	void OnTriggerStay(Collider other)
	{
		//Verifica se está colidindo com um objeto de dialogo
		if(other.gameObject.tag == "Dialog" && _dialogCall < 1)
		{
			
			_dialogCall = 1;
			
			//Pega o componente que tem os textos e salva os textos do dialogo
			myDialogText = other.gameObject.GetComponent<DialogText>();
			textReader = myDialogText.texts;
			positionDialog.x = other.transform.position.x;
			positionDialog.y = other.transform.position.y;
			name = other.gameObject.name;
			
			//Cria o primeiro dialogo
			string firstDialog = textReader[0];
			ReadText(firstDialog);
			_TextLimit = textReader.Length;
			
			if(myDialogText.isConclusion)
			{
				isConclude = true;
				saveMessage = myDialogText.message;
			}
			if(myDialogText.isNewMission)
			{
				isNew = true;
				saveMessage = myDialogText.message;
			}
			
			if(myDialogText.needAnswer)
			{
				isAnswer = true;
				posAnswer = myDialogText.Answer;
			}
			if(myDialogText.load != null)
			{
				load = myDialogText.load;
			}
			objetiva = myDialogText.isObjetiva;
			isRetributivista = myDialogText.Retributivista;
			newMissionObj = myDialogText.objLoad;
			active = myDialogText.missionNew;
			save = myDialogText.save;
			sceneLoading = myDialogText.sceneLoad;
			talk = other.gameObject;
			desative =  myDialogText.objDesactive;
			other.gameObject.active = false;
		}
		if(other.gameObject.tag == "Interact" && Input.GetKeyDown("space"))
		{
			pressStart = other.gameObject;
			Interact press = other.gameObject.GetComponent<Interact>();
			press.Active.SetActiveRecursively(true);
			interagir.SetActiveRecursively(false);
			other.gameObject.active = false;
		}
		if(other.gameObject.tag == "Interact" && countSpaceInteract < 1)
		{
			interagir.SetActiveRecursively(true);
			countSpaceInteract = 1;
		}
	}
	
	void OnTriggerExit(Collider other)
	{
		if(other.gameObject.tag == "Interact")
		{
			interagir.SetActiveRecursively(false);
			countSpaceInteract = 0;
		}
	}
	
	void ReadText(string textDialog)
	{
		if(isAnswer && _Count == posAnswer)
		{
			answerObject.SetActiveRecursively(true);	
			answerObject.SendMessage("ReceivedText",textDialog);
		}
		else
		{
			_generatorDialog.CreateDialog(textDialog,positionDialog,name,this);
			Debug.Log(textDialog);
		}
	}
	
	public void reactMessage(string dialogText)
	{
		missoesRealizadas ++;
		
		if(dialogText == "")
		{
			if(objetiva)
			{
				if(!isRetributivista)
				{
					etica.Retributivismo();
				}
				else
				{
					etica.Utilitarismo();
				}
				Destroy(talk);
				Destroy(pressStart);
			}
			
			Destroy(dialogObject);
			isConclude = false;
			_Count = 0;
			isNew = false;
			_Wait = false;
			animate.enabled = true;
			pressStart.active = true;
			isAnswer = false;
			_dialogCall = 0;
			posAnswer = 0;
			countSpaceInteract = 0;
		}
		else
		{
			_generatorDialog.CreateDialog(dialogText,positionDialog,name,this);
			isAnswer = false;
			posAnswer = 0;
			
		}
		
		if(missoesRealizadas >7)
		{
			PlayerPrefs.SetInt("Retributivistmo",etica.RetributivismoEtica);
			PlayerPrefs.SetInt("Utilitarismo",etica.UtilitarismoEtica);
			Application.LoadLevel("Resultado");
		}
		
	}
	
	
	public void dialogStart(GameObject dialogReceived)
	{
		dialogObject = dialogReceived;
		animate.enabled = false;
		_Wait = true;
		anim.Stop();
		anim.SetFrame(0);
	}
	
	public void MissionConclusion(string text)
	{
		objetivos.RemoveMission(objetivos.returnIndex(text));
		Debug.Log(objetivos.returnIndex(text));
	}
	
	void newMission(string text,string sceneLoad)
	{
		if(newMissionObj)
		{
			desative.SetActiveRecursively(false);
			load.save = save;
			load.active = active;
			newMissionObj.SetActiveRecursively(true);
			desativeNPC();
		}
		else
		{
			active.SetActiveRecursively(true);	
		}
		Debug.Log(text);
		objetivos.AddMission(text);
	}
	void desativeNPC()
	{
		foreach(GameObject game in npcs)
		{
			game.active = false;
		}	
	}
	
	public void activeNPC()
	{
		foreach(GameObject game in npcs)
		{
			game.active = true;
		}	
	}
	
	void Jump()
	{
		rigidbody.AddForce(0,_JumpAmount,0,ForceMode.Impulse);
	}

}
